<template>
  <a-tree-select
    :dropdownStyle="{ maxHeight: '80vh', overflow: 'auto' }"
    :multiple="multiple"
    :placeholder="l('FilterByPermission')"
    v-model:value="selectedPermissionVal"
    :treeData="treeData"
    @change="selectedChange($event)"
    allowClear
    showSearch
    style="width: 100%"
    treeDefaultExpandAll
    :maxTagCount="3"
  >
  </a-tree-select>
</template>

<script lang="ts">
  import { AppComponentBase } from '/@/shared/component-base';
  import { PermissionServiceProxy } from '/@/shared/service-proxies';
  import { arrayService } from '/@/shared/utils';
  import { defineComponent } from 'vue';

  export default defineComponent({
    name: 'permission-combox-new',
    mixins: [AppComponentBase],
    props: {
      value: {
        type: Array,
      },
      multiple: {
        type: Boolean,
      },
    },
    data() {
      return {
        permissionService: new PermissionServiceProxy(),
        permissions: new Array<any>(),
        treeData: new Array<any>(),
      };
    },
    emits: ['update:value', 'change'],
    computed: {
      selectedPermissionVal: {
        get() {
          return this.value;
        },
        set(val) {
          this.$emit('update:value', val);
        },
      },
    },
    mounted() {
      this.permissionService.getAllPermissions().then((result) => {
        this.permissions = result.items as Array<any>;
        this.permissions.map((item) => {
          item.value = item.name;
        }) as Array<any>;
        this.arrToTreeNode();
      });
    },
    methods: {
      arrToTreeNode() {
        this.loading = true;
        this.treeData = arrayService.arrToTreeNode(this.permissions, {
          idMapName: 'name',
          parentIdMapName: 'parentName',
          titleMapName: 'displayName',
        });

        // 延时设置子父节点checkbox关联状态，否则有父节点选中则全部选中了
        setTimeout(() => {
          this.loading = false;
        }, 500);
      },
      selectedChange(val) {
        this.selectedPermissionVal = val;
        this.$emit('change', val);
      },
    },
  });
</script>

<style scoped></style>
